package com.dpp.service.impl;

import com.dpp.entity.AddressBook;
import com.dpp.entity.CouponBook;
import com.dpp.entity.CouponImg;
import com.dpp.mapper.AddressMapper;
import com.dpp.mapper.CouponBookMapper;
import com.dpp.mapper.CouponImgMapper;
import com.dpp.mapper.OrderMapper;
import com.dpp.result.Result;
import com.dpp.service.CouponImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class CouponImgServiceImpl implements CouponImgService {
    @Autowired
    private CouponImgMapper couponImgMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CouponBookMapper couponBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public String CheckImg() {
        long time = System.currentTimeMillis();
        int random = (int) (Math.random() * Integer.MAX_VALUE);
        UUID uuid = new UUID(time, random);
        CouponImg couponImg = new CouponImg();
        couponImg.setUrl(uuid.toString());
        couponImg.setIsUse(0);
        couponImg.setCouponId(3);
        couponImgMapper.insert(couponImg);
        return uuid.toString();
    }

    @Override
    public Integer getCoupon(String url, String openid) {
      CouponImg couponImg = couponImgMapper.selectByUrlId(url);
      if(couponImg==null){
          return 0;
      }
      if(couponImg.getIsUse()==1){
          return 0;
      }else{
         List<CouponImg> couponImgs= couponImgMapper.selectByOpenid(openid);
         if(couponImgs.size()>=3){
             return -1;
          }
         AddressBook addressBook = addressMapper.selectByOpenid(openid);
         if(addressBook==null){
              return -2;
          }
          couponImg.setIsUse(1);
          couponImg.setOpenid(openid);
          couponImgMapper.updateByPrimaryKey(couponImg);
          CouponBook couponBook1 = couponBookMapper.selectByOpenidByCouponId(openid,4);
          if(couponBook1==null) {
              //添加到优惠券表中
              CouponBook couponBook = CouponBook.builder().openid(openid)
                      .count(1)
                      .couponId(CouponBook.ID4)
                      .build();
              couponBookMapper.save(couponBook);
          }else{
              //添加到优惠券表中
              couponBookMapper.updateAddCount(openid,CouponBook.ID4);
          }
          return 1;
      }
    }
}
